<template>
  <a-spin :spinning="loading">
    <div style="padding: 20px; background-color: #f5f5f5; min-height: 100vh;">
      <!-- 成绩查询区域 -->
      <div style="background: white; padding: 24px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <h2 style="margin: 0 0 20px 0; color: #333; font-size: 18px;">成绩查询</h2>
        
        <div style="display: flex; align-items: center; gap: 20px; margin-bottom: 20px;">
          <div style="display: flex; align-items: center; gap: 8px;">
            <label style="font-weight: 500; color: #333;">试卷选择：</label>
            <a-select 
              v-model:value="selectedPaper" 
              style="width: 300px;" 
              placeholder="请选择试卷"
              allow-clear
            >
              <a-select-option 
                v-for="option in paperOptions" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </a-select-option>
            </a-select>
          </div>
          
          <div style="display: flex; align-items: center; gap: 8px;">
            <label style="font-weight: 500; color: #333;">考试时间：</label>
            <a-range-picker
              v-model:value="examRange"
              style="width: 300px;"
              :placeholder="['yyyy-MM-dd','yyyy-MM-dd']"
              format="YYYY-MM-DD"
              allow-clear
            />
          </div>
        </div>
        
        <div style="display: flex; gap: 12px;">
          <a-button 
            type="primary" 
            :icon="h(SearchOutlined)" 
            size="large"
            @click="queryGrades"
          >
            查询成绩
          </a-button>
          
          <a-button 
            type="default" 
            :icon="h(DownloadOutlined)" 
            size="large"
            :loading="exportLoading"
            @click="exportExcel"
          >
            {{ exportLoading ? '导出中，请稍后...' : '导出Excel' }}
          </a-button>
          
          <a-button 
            type="default" 
            :icon="h(DownloadOutlined)" 
            size="large"
            :loading="exportPaperLoading"
            @click="exportPaperInfo"
            style="border-color: #ff4d4f; color: #ff4d4f;"
          >
            {{ exportPaperLoading ? '导出中，请稍后...' : '导出试卷信息' }}
          </a-button>
        </div>
      </div>

      <!-- 成绩列表区域 -->
      <div style="background: white; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <div style="margin-bottom: 20px;">
          <h3 style="margin: 0; color: #333; font-size: 16px;">
            当前试卷：{{ getCurrentPaperName() }}
          </h3>
        </div>
        <!-- :rowSelection="rowSelection" -->
        <a-table
          :columns="tableColumns"
          :dataSource="tableRows"
          :pagination="gradePagination"
          :scroll="{ x: 1200 }"
          rowKey="id"
          bordered
          :expandRowByClick="true"
         
        >
          <template #expandedRowRender="{ record }">
            <a-table
              :columns="innerColumns"
              :dataSource="getRowQAData(record)"
              :pagination="false"
              size="small"
              :rowKey="(r) => r.key"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'answer'">
                  <span :style="getAnswerStyle(record.answer)" class="question-score">{{ record.answer }}</span>
                </template>
              </template>
            </a-table>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex && column.dataIndex.startsWith('q_')">
              <span :style="getAnswerStyle(record[column.dataIndex])" class="question-score">{{ record[column.dataIndex] }}</span>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
import { h } from 'vue';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { ref, reactive } from 'vue';
import { onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const exportPaperLoading = ref(false);
const selectedPaper = ref<string | number | null>(null);
const examRange = ref<[Dayjs, Dayjs] | null>(null);

// 试卷下拉选项
const paperOptions = ref<Array<{label: string; value: string | number}>>([]);

// 拉取试卷列表
const fetchPaperOptions = async () => {
  try {
    const res = await fetch('http://124.222.44.60:9090/jeecg-boot/h5/sys/exam_question_bank/list?column=createTime&order=desc&pageNo=1&pageSize=9999', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    });
    const data = await res.json();
    console.log(data,"datadata")
    // 后端返回为顶层 records
    const list = data?.result.records || [];
    paperOptions.value = list.map((item: any) => ({ label: item.name, value: item.id }));
  } catch (e) {
    message.error('加载试卷列表失败');
  }
};

onMounted(async () => {
  await fetchPaperOptions();
  // 页面加载时默认查询所有数据
  await queryGrades();
});

// 获取当前试卷名称
const getCurrentPaperName = () => {
  if (!selectedPaper.value) {
    return '请选择试卷';
  }
  const selectedOption = paperOptions.value.find(option => option.value === selectedPaper.value);
  return selectedOption?.label || '未知试卷';
};

// 成绩列表列定义
const tableColumns = ref<any[]>([]);
const tableRows = ref<any[]>([]);
const selectedRecord = ref<any | null>(null);
const rowSelection = reactive({
  type: 'radio' as const,
  selectedRowKeys: [] as any[],
  onChange: (keys: any[], rows: any[]) => {
    rowSelection.selectedRowKeys = keys;
    selectedRecord.value = rows && rows.length ? rows[0] : null;
  },
});

// 写死的结构数据（与后端一致的结构）
const mockPayload = {
  "success": true,
  "message": "",
  "code": 200,
  "result": {
    "records": [
      {
        "unitName": "yyy",
        "name": "yyy",
        "score": 16,
        "titleMap": {
          "369": "您的性别",
          "370": "您的年龄",
          "371": "您的学历",
          "372": "您知道甲类传染病是哪两种吗？",
          "373": "您知道最新修订的《传染病防治法》规定的传染病种类有多少吗(",
          "374": "传染病流行是指(  )",
          "375": "您了解传染病吗？",
          "376": "您觉得日常生活中了解传染病知识的途径多吗？",
          "377": "您主要通过什么途径了解传染病知识？",
          "379": "预防传染病的主要措施有什么(  )",
          "380": "出门在外应如何预防新型冠状病毒感染(  )"
        },
        "answerMap": {
          "369": "错",
          "370": "错",
          "371": "错",
          "372": "对",
          "373": "错",
          "374": "对",
          "375": "错",
          "376": "错",
          "377": "错",
          "379": "对",
          "380": "对"
        },
        "createTime": "2025-09-03 11:37:38"
      },
      {
        "unitName": "yyy",
        "name": "yyy",
        "score": 11,
        "titleMap": {
          "369": "您的性别",
          "370": "您的年龄",
          "371": "您的学历",
          "372": "您知道甲类传染病是哪两种吗？",
          "373": "您知道最新修订的《传染病防治法》规定的传染病种类有多少吗(",
          "374": "传染病流行是指(  )",
          "375": "您了解传染病吗？",
          "376": "您觉得日常生活中了解传染病知识的途径多吗？",
          "377": "您主要通过什么途径了解传染病知识？",
          "379": "预防传染病的主要措施有什么(  )",
          "380": "出门在外应如何预防新型冠状病毒感染(  )"
        },
        "answerMap": {
          "369": "错",
          "370": "错",
          "371": "错",
          "372": "对",
          "373": "错",
          "374": "对",
          "375": "错",
          "376": "错",
          "377": "错",
          "379": "错",
          "380": "对"
        },
        "createTime": "2025-09-02 16:08:20"
      },
      {
        "unitName": "123",
        "name": "456",
        "score": 11,
        "titleMap": {
          "369": "您的性别",
          "370": "您的年龄",
          "371": "您的学历",
          "372": "您知道甲类传染病是哪两种吗？",
          "373": "您知道最新修订的《传染病防治法》规定的传染病种类有多少吗(",
          "374": "传染病流行是指(  )",
          "375": "您了解传染病吗？",
          "376": "您觉得日常生活中了解传染病知识的途径多吗？",
          "377": "您主要通过什么途径了解传染病知识？",
          "379": "预防传染病的主要措施有什么(  )",
          "380": "出门在外应如何预防新型冠状病毒感染(  )"
        },
        "answerMap": {
          "369": "错",
          "370": "错",
          "371": "错",
          "372": "对",
          "373": "错",
          "374": "错",
          "375": "错",
          "376": "错",
          "377": "错",
          "379": "对",
          "380": "对"
        },
        "createTime": "2025-09-02 16:02:14"
      },
      {
        "unitName": "43535",
        "name": "3545",
        "score": 5,
        "titleMap": {
          "369": "您的性别",
          "370": "您的年龄",
          "371": "您的学历",
          "372": "您知道甲类传染病是哪两种吗？",
          "373": "您知道最新修订的《传染病防治法》规定的传染病种类有多少吗(",
          "374": "传染病流行是指(  )",
          "375": "您了解传染病吗？",
          "376": "您觉得日常生活中了解传染病知识的途径多吗？",
          "377": "您主要通过什么途径了解传染病知识？",
          "379": "预防传染病的主要措施有什么(  )",
          "380": "出门在外应如何预防新型冠状病毒感染(  )"
        },
        "answerMap": {
          "369": "错",
          "370": "错",
          "371": "错",
          "372": "错",
          "373": "错",
          "374": "对",
          "375": "错",
          "376": "错",
          "377": "错",
          "379": "错",
          "380": "错"
        },
        "createTime": "2025-09-02 10:03:22"
      },
      {
        "unitName": "测试",
        "name": "001",
        "score": 5,
        "titleMap": {
          "369": "您的性别",
          "370": "您的年龄",
          "371": "您的学历",
          "372": "您知道甲类传染病是哪两种吗？",
          "373": "您知道最新修订的《传染病防治法》规定的传染病种类有多少吗(",
          "374": "传染病流行是指(  )",
          "375": "您了解传染病吗？",
          "376": "您觉得日常生活中了解传染病知识的途径多吗？",
          "377": "您主要通过什么途径了解传染病知识？",
          "378": "如果您对传染病不了解，原因在于"
        },
        "answerMap": {
          "369": "错",
          "370": "错",
          "371": "错",
          "372": "错",
          "373": "对",
          "374": "错",
          "375": "错",
          "376": "错",
          "377": "错",
          "378": ""
        },
        "createTime": "2025-09-01 16:21:55"
      }
    ],
    "total": 5,
    "size": 10,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "maxLimit": null,
    "countId": null,
    "pages": 1
  },
  "timestamp": 1756891326245
};

// 构建表格数据（动态数据）
const buildTableByData = (result: any) => {
  const records = result.records || [];
  if (!records.length) {
    tableColumns.value = [];
    tableRows.value = [];
    gradePagination.total = 0;
    return;
  }
  
  // 基础列
  const baseCols = [
    { title: '考生单位', dataIndex: 'unitName', key: 'unitName', width: 150 },
    { title: '考生姓名', dataIndex: 'name', key: 'name', width: 120 },
    { title: '考试成绩', dataIndex: 'score', key: 'score', width: 100 },
    { title: '提交时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  ];
  // 主表仅展示基础列，题目在展开区域展示
  tableColumns.value = [...baseCols];

  // 行数据
  tableRows.value = records.map((rec: any, idx: number) => {
    const row: any = {
      id: idx + 1,
      unitName: rec.unitName,
      name: rec.name,
      score: rec.score,
      createTime: rec.createTime || '',
      _titleMap: rec.titleMap || {},
      _answerMap: rec.answerMap || {},
    };
    return row;
  });
  
  // 更新分页信息
  gradePagination.total = result.total || records.length;
  gradePagination.current = result.current || 1;
  gradePagination.pageSize = result.size || 10;
};

// 构建表格数据（Mock数据，用于初始化）
const buildTableByMock = () => {
  const records = mockPayload.result.records || [];
  if (!records.length) {
    tableColumns.value = [];
    tableRows.value = [];
    return;
  }
  // 基础列
  const baseCols = [
    { title: '考生单位', dataIndex: 'unitName', key: 'unitName', width: 150 },
    { title: '考生姓名', dataIndex: 'name', key: 'name', width: 120 },
    { title: '考试成绩', dataIndex: 'score', key: 'score', width: 100 },
    { title: '提交时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  ];
  // 主表仅展示基础列，题目在展开区域展示
  tableColumns.value = [...baseCols];

  // 行数据
  tableRows.value = records.map((rec, idx) => {
    const row: any = {
      id: idx + 1,
      unitName: rec.unitName,
      name: rec.name,
      score: rec.score,
      createTime: rec.createTime || '',
      _titleMap: rec.titleMap || {},
      _answerMap: rec.answerMap || {},
    };
    // 不再把题目作为主表列
    return row;
  });
};

// 展开行内表头
const innerColumns = [
  { title: '题目', dataIndex: 'title', key: 'title', width: 360 },
  { title: '回答', dataIndex: 'answer', key: 'answer', width: 120 },
];

// 将一行记录的 titleMap/answerMap 转为数组供内嵌表渲染
const getRowQAData = (record: any) => {
  const titleMap = record?._titleMap || {};
  const answerMap = record?._answerMap || {};
  return Object.entries(titleMap)
    .sort(([a], [b]) => Number(a) - Number(b))
    .map(([qid, title]: any, idx: number) => ({
      key: `${record.id}_${qid}`,
      title: String(title),
      answer: typeof answerMap[qid] === 'string' ? answerMap[qid] : '',
    }));
};

// 分页配置
const gradePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `显示${range[0]}到${range[1]}条,共${total}条记录`,
  onChange: async (page: number, pageSize: number) => {
    gradePagination.current = page;
    gradePagination.pageSize = pageSize;
    
    // 重新查询数据（支持可选参数）
    loading.value = true;
    try {
      // 处理试卷参数
      const bankId = selectedPaper.value || '';
      
      // 处理时间参数
      let startTime = '';
      let endTime = '';
      if (examRange?.value && examRange.value.length === 2) {
        const [start, end] = examRange.value;
        startTime = start.format('YYYY-MM-DD');
        endTime = end.format('YYYY-MM-DD');
      }
      
      const result = await fetchScoreList(bankId, startTime, endTime, page, pageSize);
      buildTableByData(result);
    } catch (e) {
      console.error('分页查询失败：', e);
      message.error('分页查询失败，请重试');
    } finally {
      loading.value = false;
    }
  }
});

// 根据答案值返回样式：对=绿色，错=红色
const getAnswerStyle = (val: string) => {
  if (val === '对') {
    return { color: '#52c41a', fontWeight: 'bold' };
  }
  if (val === '错') {
    return { color: '#ff4d4f', fontWeight: 'bold' };
  }
  return {};
};

// 查询成绩数据
const fetchScoreList = async (bankId: string | number, startTime: string, endTime: string, pageNo: number = 1, pageSize: number = 10) => {
  try {
    const params = new URLSearchParams({
      bankId: String(bankId),
      startTime,
      endTime,
      pageNo: String(pageNo),
      pageSize: String(pageSize)
    });
    
    const res = await fetch(`http://124.222.44.60:9090/jeecg-boot/h5/sys/queryPaperScoreList?${params}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    });
    
    const data = await res.json();
    console.log('成绩查询结果：', data);
    
    if (data.success && data.result) {
      return data.result;
    } else {
      throw new Error(data.message || '查询失败');
    }
  } catch (e) {
    console.error('查询成绩失败：', e);
    throw e;
  }
};

// 查询成绩
const queryGrades = async () => {
  loading.value = true;
  
  try {
    // 重置分页到第一页
    gradePagination.current = 1;
    
    // 处理试卷参数
    const bankId = selectedPaper.value || '';
    
    // 处理时间参数
    let startTime = '';
    let endTime = '';
    if (examRange?.value && examRange.value.length === 2) {
      const [start, end] = examRange.value;
      startTime = start.format('YYYY-MM-DD');
      endTime = end.format('YYYY-MM-DD');
    }
    
    console.log('查询参数：', {
      bankId,
      startTime,
      endTime,
      pageNo: 1,
      pageSize: gradePagination.pageSize
    });
    
    const result = await fetchScoreList(bankId, startTime, endTime, 1, gradePagination.pageSize);
    buildTableByData(result);
    message.success('查询成功');
  } catch (e) {
    console.error('查询失败：', e);
    message.error('查询失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 导出Excel：改为调后端接口生成并下载
const exportExcel = async () => {
  if (!selectedPaper.value) {
    message.warning('请先选择试卷后再导出');
    return;
  }
  exportLoading.value = true;

  try {
    // 与查询参数保持一致
    const bankId = selectedPaper.value || '';
    let startTime = '';
    let endTime = '';
    if (examRange?.value && examRange.value.length === 2) {
      const [start, end] = examRange.value;
      startTime = start.format('YYYY-MM-DD');
      endTime = end.format('YYYY-MM-DD');
    }
    const pageNo = gradePagination.current || 1;
    const pageSize = gradePagination.pageSize || 10;

    const params = new URLSearchParams({
      bankId: String(bankId),
      startTime,
      endTime,
      pageNo: String(pageNo),
      pageSize: String(pageSize)
    });

    const res = await fetch(`http://124.222.44.60:9090/jeecg-boot/h5/sys/exportXls?${params}`, {
      method: 'GET',
      headers: {
        // 接受二进制文件
        'Accept': 'application/octet-stream'
      }
    });

    if (!res.ok) {
      // 尝试读取错误信息
      try {
        const errJson = await res.json();
        throw new Error(errJson.message || '导出失败');
      } catch (_) {
        throw new Error('导出失败');
      }
    }

    // 从响应头解析文件名
    const disposition = res.headers.get('content-disposition') || '';
    let filename = '导出.xlsx';
    const match = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i);
    if (match) {
      const encoded = match[1] || match[2];
      try {
        filename = decodeURIComponent(encoded);
      } catch {
        filename = encoded;
      }
    }

    const blob = await res.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);

    message.success('导出成功');
  } catch (e) {
    console.error(e);
    message.error((e as any)?.message || '导出失败，请重试');
  } finally {
    exportLoading.value = false;
  }
};

// 导出试卷信息
const exportPaperInfo = async () => {
  if (!selectedPaper.value) {
    message.warning('请先选择试卷后再导出');
    return;
  }
  exportPaperLoading.value = true;

  try {
    const bankId = selectedPaper.value;
    
    const params = new URLSearchParams({
      bankId: String(bankId)
    });

    const res = await fetch(`http://124.222.44.60:9090/jeecg-boot/h5/sys/exportXlsV1?${params}`, {
      method: 'GET',
      headers: {
        // 接受二进制文件
        'Accept': 'application/octet-stream'
      }
    });

    if (!res.ok) {
      // 尝试读取错误信息
      try {
        const errJson = await res.json();
        throw new Error(errJson.message || '导出失败');
      } catch (_) {
        throw new Error('导出失败');
      }
    }

    // 从响应头解析文件名
    const disposition = res.headers.get('content-disposition') || '';
    let filename = '试卷信息.xlsx';
    const match = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i);
    if (match) {
      const encoded = match[1] || match[2];
      try {
        filename = decodeURIComponent(encoded);
      } catch {
        filename = encoded;
      }
    }

    const blob = await res.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);

    message.success('试卷信息导出成功');
  } catch (e) {
    console.error(e);
    message.error((e as any)?.message || '导出失败，请重试');
  } finally {
    exportPaperLoading.value = false;
  }
};
</script>

<style scoped>
.question-score {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  text-align: center;
  min-width: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ant-table {
    font-size: 12px;
  }
  
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    padding: 8px 4px;
  }
}
</style>
